import java.io.File;
import java.io.IOException;

import javabean.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.InitServlet;
import util.MultipartRequest;
import util.Constant;
import util.PubFun;

public class SimpleUploaderCtrl extends HttpServlet {

	private static final long serialVersionUID = 1L;
//fck上传文件
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html; charset=UTF-8");
		resp.setHeader("Cache-Control","no-cache");
		HttpSession session = req.getSession(true);
		UserInfo user = (UserInfo) session.getAttribute("userInfo");
		if (user == null) {
			PubFun.ajaxPrintUpStr("alert('页面失效；请重新登陆。');parent.parent.parent.location='"
					+ req.getContextPath() + "/" + Constant.REDIRECT_LOGIN_PAGE + "';", resp);
			return;
		}		

		String typeStr = req.getParameter("Type");

		String currentPath = Constant.UPLOAD_PATH + "/" + user.getName() + "/"
				+ typeStr + "/" + PubFun.getDateTime("yyyy-MM", null);
		String currentDirPath = InitServlet.WEB_SITE_PATH + currentPath;
		File current = new File(currentDirPath);
		if (!current.exists()) {
			current.mkdirs();
		}
		currentPath = InitServlet.WEB_SITE_URL + currentPath;

		String retVal = "0";
		String fileUrl = "";
		String errorMessage = "";
		String fileName = "";

		try {
			req = new MultipartRequest(req, user.getId());
			File upFile = ((MultipartRequest) req).getFile("NewFile");
			if (upFile != null) {
				fileName = ((MultipartRequest) req).getFileName(upFile);
				String nameWithoutExt = fileName.substring(0, fileName
						.lastIndexOf("."));
				String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
				File pathToSave = new File(currentDirPath, fileName);
				fileUrl = currentPath + "/" + fileName;
				int counter = 1;
				while (pathToSave.exists()) {
					fileName = nameWithoutExt + "(" + counter + ")" + "."
							+ ext;
					fileUrl = currentPath + "/" + fileName;
					retVal = "201";
					pathToSave = new File(currentDirPath, fileName);
					counter++;
				}
				PubFun.saveAs(upFile, currentDirPath
						+ "/" + fileName);
			} else {
				retVal = "202";
			}
		} catch (Exception ex) {
			retVal = "203";
		} finally {
			if (req instanceof MultipartRequest) {
				((MultipartRequest) req).deleteTemporaryFile();
			}
		}
		
		String str = "OnUploadCompleted(" + retVal + ",'" + fileUrl + "','"
		+ fileName + "','" + errorMessage + "');";

		PubFun.ajaxPrintUpStr(str, resp);
	}

}

